#include "doublelist.h"
#include <stdlib.h>
#include <stdio.h>

Dlist_t *createDlist() {
    Dlist_t *header= NULL;
    header=malloc(sizeof(Dlist_t));
    if (header == NULL) {
        fprintf(stderr, "Error allocating memory for Dlist_t\n");
        return NULL;
    }
    header->val=0;
    header->next=header->prev=header;
    return header;
}

static void removeDnode(Dnode_t *prev, Dnode_t *next) {
    prev->next=next;
    next->prev=prev;
}

void releaseDlist(Dlist_t *header) {
    if (header!= NULL) {
        Dnode_t *p=header->next,*temp=NULL;
        while(p!=header) {
           temp=p;
           removeDnode(temp->prev, temp->next);
           free(temp);

            p=header->next;
        }
        free(header);
    }


}


static void addDnode(Dnode_t *new_node, Dnode_t *prev, Dnode_t *next) {
    new_node->next=next;
    new_node->prev=prev;
    next->prev=new_node;
    prev->next=new_node;
}


int insertDlistHead(Dlist_t *header, Element_t value) {
    if (header == NULL) {
        printf("Error: header is NULL\n");
        return -1;
    }

    Dnode_t *new_node=malloc(sizeof(Dnode_t));
    if (new_node == NULL) {
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }

    new_node->val = value;
    addDnode(new_node, header, header->next);
    ++header->val;
    return 0;
}

int insertDlistTail(Dlist_t *header, Element_t value) {
    if (header == NULL) {
        printf("Error: header is NULL\n");
        return -1;
    }

    Dnode_t *new_node=malloc(sizeof(Dnode_t));
    if (new_node == NULL) {
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }

    new_node->val = value;
    addDnode(new_node, header->prev, header);
    ++header->val;
    return 0;
}


int deleteDlistValue(Dlist_t *header, Element_t value) {
    if (header == NULL) {
        printf("Error: header is NULL\n");
        return -1;
    }

    Dnode_t *p=header->next;
    while(p!=header) {
        if(p->val==value)  break;
        p=p->next;
    }

    if(p==header) {printf("value not found\n");return 0;}

    removeDnode(p->prev, p->next);
    free(p);
    --header->val;

    return 0;
}

void showDlist(const Dlist_t *header) {
    if (header == NULL) {
        printf("Error: header is NULL\n");
        return;
    }
    Dnode_t *p=header->next;
    printf("DList's size is %d\n", header->val);
    while(p!=header) {
        printf("%d\t", p->val);
        p=p->next;
    }
    printf("\n");
}
